﻿using Furion.FriendlyException;
using Magic.Core.Entity;
using Mapster;
using System.Threading.Tasks;

namespace Magic.Core.Service;

/// <summary>
/// 文章服务
/// </summary>W
public class SysArticleService : ISysArticleService
{
    private readonly SqlSugarRepository<SysArticle> _sysArticleRep;

    public SysArticleService(SqlSugarRepository<SysArticle> sysArticleRep)
    {
        _sysArticleRep = sysArticleRep;
    }

    /// <summary>
    /// 分页查询文章
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<PageList<SysArticlePageOutput>> PageList(QuerySysArticleInput input)
    {
        var articles = await _sysArticleRep.AsQueryable()
                                        .WhereIF(!string.IsNullOrWhiteSpace(input.SearchValue), u => u.Title.Contains(input.SearchValue.Trim()) || u.Content.Contains(input.SearchValue.Trim()))
                                        .WhereIF(input.Type > 0, u => u.Type == input.Type)
                                        .Select<SysArticlePageOutput>()
                                        .ToPagedListAsync(input.PageNo, input.PageSize);
        return articles.McPagedResult();
    }



    /// <summary>
    /// 增加文章
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Add(AddSysArticleInput input)
    {
        var article = input.Adapt<SysArticle>();
        await _sysArticleRep.InsertAsync(article);
    }

    /// <summary>
    /// 删除文章
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Delete(Core.PrimaryKeyParam input)
    {
        var article = await _sysArticleRep.SingleAsync(input.Id);
        if (article.IsNullOrZero())
            throw Oops.Oh("文章不存在");
        await _sysArticleRep.DeleteAsync(article);
    }

    /// <summary>
    /// 更新文章
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task Update(EditSysArticleInput input)
    {
        var article = await _sysArticleRep.SingleAsync(input.Id);
        if (article.IsNullOrZero())
            throw Oops.Oh("文章不存在");
        article = input.Adapt<SysArticle>();
        await _sysArticleRep.UpdateAsync(article);
    }

    /// <summary>
    /// 获取文章详情
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<SysArticleDetailOutput> Get(Core.PrimaryKeyParam input)
    {
        var article = await _sysArticleRep.Where(m=>m.Id==input.Id).Select<SysArticleDetailOutput>().FirstAsync();
        if (article.IsNullOrZero())
            throw Oops.Bah("文章不存在");
        return article;
    }

}
